package pers.qianyu.domain.common;

import io.swagger.annotations.*;
import lombok.*;
import pers.qianyu.exception.*;

import java.io.*;

/**
 * @author mizzle rain
 * @date 2020-10-11 22:18
 */
@ApiModel(value = "统一返回结果实体", description = "封装统一返回结果信息")
@Data
public class HttpResult<T> implements Serializable {
    private static final long serialVersionUID = 5520873212072402836L;
    /**
     * 请求是否成功
     */
    @ApiModelProperty(value = "请求是否成功", example = "true")
    private Boolean success;
    /**
     * 编码
     */
    @ApiModelProperty(value = "响应编码", example = "0")
    private Integer code;
    /**
     * 描述信息
     */
    @ApiModelProperty(value = "描述信息", example = "请求成功")
    private String message;
    /**
     * 请求返回结果
     */
    @ApiModelProperty(value = "请求返回结果")
    private T data;

    /**
     * 请求成功的返回信息
     *
     * @param message 返回结果描述
     * @param <T>     返回结果类型
     * @return 返回信息的封装
     */
    public static <T> HttpResult<T> okWithMessage(String message) {
        HttpResult<T> httpResult = new HttpResult<>();
        httpResult.setSuccess(Boolean.TRUE);
        httpResult.setMessage(message);
        return httpResult;
    }

    /**
     * 请求成功的返回信息
     *
     * @param data 返回结果
     * @param <T>    返回结果类型
     * @return 返回信息的封装
     */
    public static <T> HttpResult<T> okWithData(T data) {
        HttpResult<T> httpResult = new HttpResult<>();
        httpResult.setSuccess(Boolean.TRUE);
        httpResult.setData(data);
        return httpResult;
    }

    /**
     * 请求失败的返回信息
     *
     * @param message 失败信息
     * @param <T>     返回结果类型
     * @return 返回信息的封装
     */
    public static <T> HttpResult<T> error(Integer code, String message) {
        HttpResult<T> httpResult = new HttpResult<>();
        httpResult.setSuccess(Boolean.FALSE);
        httpResult.setCode(code);
        httpResult.setMessage(message);
        return httpResult;
    }

    /**
     * 请求失败的返回信息
     *
     * @param errorCodeEnum 异常枚举
     * @param <T>           返回结果类型
     * @return 返回信息的封装
     */
    public static <T> HttpResult<T> error(ErrorCodeEnum errorCodeEnum) {
        HttpResult<T> httpResult = new HttpResult<>();
        httpResult.setSuccess(Boolean.FALSE);
        httpResult.setCode(errorCodeEnum.getCode());
        httpResult.setMessage(errorCodeEnum.getMessage());
        return httpResult;
    }
}
